﻿using Common;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
using WPTrek.Gui.Events;
using WPTrek.Gui.Views;

namespace WPTrek.Gui.Controllers
{
    public class GuiController : ControllerBase
    {
        public GuiController(IUnityContainer container, IEventAggregator eventAggregator, IRegionManager regionManager)
            : base(container, eventAggregator, regionManager)
        {
            eventAggregator.GetEvent<SwitchViewEvent>().Subscribe(OnSwitchViewEvent, true);

            RegisterViews();
        }

        private void RegisterViews()
        {
            var mainRegion = GetMainRegion();
            mainRegion.Add(container.Resolve<MenuView>(), ViewNames.MainMenuView);
            mainRegion.Add(container.Resolve<GameView>(), ViewNames.GameView);
            mainRegion.Add(container.Resolve<WorldBuilderView>(), ViewNames.WorldBuilderView);
        }

        private IRegion GetMainRegion()
        {
            return regionManager.Regions[RegionNames.MainRegion];
        }

        private void OnSwitchViewEvent(string viewName)
        {
            SwitchView(viewName);
        }

        private void SwitchView(string viewName)
        {
            var region = GetMainRegion();
            var view = region.GetView(viewName);
            if (view != null)
            {
                region.Activate(view);
            }
        }
    }
}
